<template>
	<view class="loginPage col-3e bg-fff">
		<view class="top"></view>
		<view class="content">
			<view class="title">欢迎登录新房超市</view>
            <u-form :model="model" :rules="rules" ref="uForm" label-width="45">
                <u-form-item leftIcon="phone-fill" label=" " label-width="20" prop="phone">
                    <u-input class="inp" v-model="model.phone" type="number" border="none" placeholder="请输入手机号"></u-input>
                </u-form-item>

                <up-form-item leftIcon="lock-fill" label="" prop="code" labelWidth="20">
                    <up-input v-model="model.code" type="text" border="none" placeholder="请填写验证码"></up-input>
                    <up-button
                        slots="right"
                        :customStyle="customStyBtn"
                        @click.stop="getCode"
                        :text="codeTips"
                        size="mini"
                        style="flex: 0.5;"
                        :disabled="codeDisabled"
                    ></up-button>
                </up-form-item>
            </u-form>
			<button @tap="submit" class="phoneLogin getCaptcha">
                <text class="btnTxt">手机号登录</text>
            </button>
            
            <block v-if="historyPhone">
                <button type="primary" :disabled="!checkAgreement" @tap="fastLoginin" class="getCaptcha">
                    <text class="btnTxt">一键登录</text>
                </button>
            </block>
            <block v-else>
                <button type="primary" class="getCaptcha" open-type="getPhoneNumber|agreePrivacyAuthorization" :disabled="!checkAgreement" @getphonenumber="getUserPhoneNum" @agreeprivacyauthorization="handleAgreePrivacyAuthorization">
                    <text class="btnTxt">手机号快捷登录</text>
                </button>
            </block>
		</view>
		<view class="buttom">
			<view class="agreement flex col-grey font12">
                <u-checkbox v-model="checkAgreement" usedAlone active-color="#007235" size="15" @change="checkboxChange"></u-checkbox>
                <view class="top-5">
                    同意并遵守<text class="col-theme" @click="toAgreement">新房超市用户协议、</text><text class="col-theme" @click="toPolicy">隐私政策。</text>
                </view>
			</view>
		</view>
        <up-code ref="uCode" @change="codeChange" seconds="60" @start="codeDisabled = true" @end="codeDisabled = false"></up-code>
	</view>
</template>

<script>
import { mapState, mapActions } from 'pinia';
import { useConfigStore, useUserInfoStore } from '@/store/index';
import { getVerificationCode, loginAPI, checkUserAuthPhone, decryptPhoneApi } from '@/common/api';
import { getUserInfo } from '@/common/api/user';
import { openAgreement, openPolicy } from '@/common/utils/docts';
export default {
	data() {
		return {
            historyPhone: '',
            model: {
                phone: '',
                code: ''
            },
            customStyBtn: {
                position: 'absolute',
                right: '10rpx',
                top: '0',
                bottom: '0',
                margin: 'auto',
                width: 'auto',
                zIndex: '99',
            },
            codeDisabled: false,
            codeTips: '获取验证码',
            checkAgreement: false,
            rules: {
                phone: [
                    {
                        required: true,
                        message: '请输入手机号',
                        trigger: ['change','blur'],
                    },
                    {
                        validator: (rule, value, callback) => {
                            // 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
                            return uni.$u.test.mobile(value);
                        },
                        message: '手机号码不正确',
                        // 触发器可以同时用blur和change，二者之间用英文逗号隔开
                        trigger: ['change','blur'],
                    }
                ],
                code: [
                    {
                        required: true,
                        type: 'string',
                        message: '请输入验证码',
                        trigger: ['blur'],
                    }
                ]
            }
		}
	},
    computed:{
        ...mapState(useConfigStore, ['puid', 'platform']),
        ...mapState(useUserInfoStore, ['userInfo']),
    },
    onReady() {
        //#ifdef MP-WEIXIN || MP-BAIDU
        this.$refs.uForm.setRules(this.rules);
        //#endif
    },
    onLoad(options) {
        const that = this;
        uni.$check_and_login(function() {
            that.init()
        })
    },
    onShareAppMessage(res) {
        return {
            title: `选楼盘，开盘日历，查限购，查积分，一手掌握`,
            path: '/pages/tabBar/home/index'
        }
    },
	methods: {
        ...mapActions(useUserInfoStore, ['setUserInfo']),
        //初始化
        init() {
            if(this.userInfo.phone) {
                this.model.phone = this.userInfo.phone;
            }
            checkUserAuthPhone().then(res => {
                if(res.status === 0) {
                    this.historyPhone = res.detail;
                }
            })
        },

        // 勾选版权协议
        checkboxChange(e) {
            this.checkAgreement = e;
            this.model.agreement = e;
        },

        // 获取验证码
        getCode() {
            if(this.model.phone === '') {
                uni.$u.toast('请输入手机号');
                return
            }
            const that = this;

            if(this.$refs.uCode.canGetCode) {
                uni.showLoading({
                    title: '正在获取验证码',
                    mask: true
                })
                uni.login({
                    success: async (data) => {
                        let reqData = {
                            code: data.code,
                            puid: that.puid,
                            type: that.platform
                        }
                        //#ifdef MP-TOUTIAO
                        if(data.isLogin){
                            reqData = {code: data.code, type: that.platform}
                        }else{
                            reqData = {code: data.anonymousCode, type: 'toutiao_anonymous'}
                        }
                        //#endif
                        
                        let updateRes = await loginAPI({
                            ...reqData,
                            login: false
                        })
                        
                        await that.setTokenStorage(updateRes.detail);
                        
                        let codeRes = await getVerificationCode({
                            type: 'login',
                            phone: that.model.phone
                        })
                        
                        uni.hideLoading();
                        
                        if(codeRes.status === 0) {
                            uni.$u.toast('验证码已发送');
                            this.$refs.uCode.start();
                        }else {
                            uni.$u.toast(codeRes.detail);
                        }
                    },
                    fail: (err) => {
                        uni.hideLoading();
                        uni.$u.toast(err);
                    }
                })
            } else {
                uni.$u.toast('倒计时结束后再发送');
            }
        },
        codeChange(text) {
            this.codeTips = text;
        },

        //用户同意隐私协议事件回调
        handleAgreePrivacyAuthorization(e) {
            this.getUserPhoneNum(e);
        },
        
        /**
         * 手机号授权
         * 首先login获取code,请求登录更新token
         * 再次请求登录更新用户信息
         * */
        getUserPhoneNum(e){
            const that = this;
            let { errMsg, iv, encryptedData, code='', cloudId } = e.detail;
            if(errMsg == "getPhoneNumber:ok"){
            	uni.showLoading({
            		title: '处理中...',
            		mask: true
            	})

                uni.login({
                    success: async (data) => {
                        let updateRes = await loginAPI({
                            code: data.code,
                            puid: that.puid,
                            type: that.platform,
                            login: true
                        })
                        
                        await that.setTokenStorage(updateRes.detail);
                        await decryptPhoneApi({
                            iv,
                            code,
                            encryptedData,
                            puid: that.puid
                        })
                        
                        let userInfoRes = await getUserInfo();
                        if(userInfoRes.status === 0) {
                            await that.updateStorageUser(userInfoRes.detail)
                            uni.navigateBack({
                                delta: 1
                            })
                        }
                        uni.hideLoading();
                    },
                    fail: (err) => {
                        uni.hideLoading();
                        uni.$u.toast(err);
                    }
                })
            }
        },
        
        //设置缓存更新token
        setTokenStorage(data) {
            return new Promise((resolve) => {
                uni.setStorage({
                    key: 'token',
                    data: {
                        token: data.token,
                        jwttoken: data.jwttoken,
                        expire: data.expire*1000,
                        created: (new Date()).getTime()
                    },
                    success: () => {
                        resolve('success')
                    }
                })
            })
        },

        //一键登录,历史登录过或授权过手机号
        async fastLoginin() {
            const that = this;
            try {
                uni.showLoading({
                    title: '处理中...',
                    mask: true
                })
                const loginResult = await uni.login();
                const updateRes = await loginAPI({
                    type: that.platform,
                    code: loginResult.code,
                    puid: that.puid,
                    login: true
                })
                
                await that.setTokenStorage(updateRes.detail);
                
                const userInfoRes = await getUserInfo();
                if(userInfoRes.status === 0) {
                    await that.updateStorageUser(userInfoRes.detail)
                    uni.navigateBack({
                        delta: 1
                    })
                }
            } catch(err) {
                uni.$u.toast(err);
            } finally {
                uni.hideLoading();
            }
        },
        
        //提交表单
		submit() {
            const that = this;
            this.$refs.uForm.validate().then(valid => {
                if (valid) {
                    if(!that.model.agreement) {
                        uni.$u.toast('请勾选协议');
                        return
                    };
                    that.codeLogin({
                        phone: that.model.phone,
                        code: that.model.code,
                        puid: that.puid,
                        login: true
                    })
                }
            })
		},
        
        //更新store和storage内的用户信息
        updateStorageUser(info) {
            return new Promise((resolve, reject) => {
                this.setUserInfo({
                    ...info
                });
                
                uni.setStorage({
                    key: 'userInfo',
                    data: info,
                    success: () => {
                        resolve('succ')
                    }
                })
            })
        },
        
        //验证码登录请求
        async codeLogin(data) {
            let loginRes = await loginAPI(data);
            if(loginRes.status === 0) {
                await this.setTokenStorage(loginRes.detail);
            }else {
                uni.$u.toast(loginRes.detail);
                return
            }
            
            let userInfoRes = await getUserInfo();
            if(userInfoRes.status === 0) {
                await this.updateStorageUser(userInfoRes.detail)
                uni.navigateBack({
                    delta: 1
                })
            }
        },
        
        //协议
        toAgreement(){
            openAgreement();
        },
        
        //政策
        toPolicy(){
            openPolicy();
        }
	}
};
</script>

<style lang="scss" scoped>
::v-deep .u-form-item__body__right__content__slot{
    position: relative;
}
.loginPage {
    min-height: 100vh;
    overflow: hidden;
    line-height: 1.3;
	.content {
		width: 600rpx;
		margin: 80rpx auto 0;
		.title {
			text-align: left;
			font-size: 60rpx;
			font-weight: 500;
			margin-bottom: 100rpx;
		}
		.inp {
			text-align: left;
			margin-bottom: 10rpx;
			padding-bottom: 6rpx;
		}
        .phoneLogin{
            background-color: $theme-color;
        }
		.getCaptcha {
            margin-top: 40rpx;
			color: #FFFFFF;
			border: none;
			font-size: 30rpx;
			padding: 12rpx 0;
			&::after {
				border: none;
			}
            .btnTxt{
                margin-left: 10rpx;
            }
		}
	}
   
	.buttom {
		margin: 40rpx 80rpx;
        .agreement{
            align-items: flex-start;
            justify-content: flex-start;
        }
	}
}
</style>